package com.thymeleaf.demo.controller;

import com.thymeleaf.demo.dto.LoginDto;
import com.thymeleaf.demo.model.MallAdmin;
import com.thymeleaf.demo.myexception.MyExcption;
import com.thymeleaf.demo.service.impl.LoginServiceImpl;
import com.thymeleaf.demo.util.result.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("mall/admin/login")
public class LoginController {

    @Autowired
    LoginServiceImpl loginService;

    @GetMapping("")
    public ModelAndView login(){
        return new ModelAndView("login/login");
    }

    @PostMapping()
    public ModelAndView doLogin(@Validated LoginDto loginDto, HttpServletRequest request, HttpSession session){
        ModelAndView modelAndView = new ModelAndView();
        try {
            MallAdmin admin = loginService.doLogin(loginDto);
//            HttpSession session = request.getSession();
            session.setAttribute("admin", admin);
            // 登陆成功进入用户列表页面
            modelAndView.setViewName("redirect:/mall/admin/user/list");
        } catch (MyExcption myExcption) {
            // 登陆失败,跳回登陆页面
            modelAndView.setViewName("login/login");
            modelAndView.addObject("errorMsg", ResultEnum.getResultByCode(Integer.parseInt(myExcption.getMessage())).getMsg());
        }

        return modelAndView;
    }

    @GetMapping("logout")
    public ModelAndView logout(HttpServletRequest request, HttpSession session){
        session.removeAttribute("admin");
        request.removeAttribute("errorMsg");
        return new ModelAndView("login/login");
    }

}
